package com.ddstation.verifycode.service;

import com.ddstation.common.shortmail.service.ShortMailService;
import com.ddstation.security.property.SignatureProperties;
import com.ddstation.security.util.MD5Util;
import com.ddstation.verifycode.entity.VerifycodeEntity;
import com.ddstation.verifycode.property.VerifyCodeProperties;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.Date;
import java.util.Random;

@Service @Lazy
public class VerifycodeServiceImpl implements VerifycodeService {

	@Override
	public VerifycodeEntity create(String phone, int integererval) {
		// TODO Auto-generated method stub
		VerifycodeEntity v = new VerifycodeEntity();
		// 生产验证码
		Random random = new Random();
		StringBuilder verifyCode = new StringBuilder();
		int digit = VerifyCodeProperties.VERIFY_CODE_DIGIT;
		while(digit-- > 0) {
			int a = random.nextInt(10);
			verifyCode.append(a);
		}
		v.setTimelimit(integererval * 1000 + System.currentTimeMillis());
		v.setPhone(phone);
		try {
			v.setDatasign(MD5Util.md5Encode(verifyCode.toString() + phone + v.getTimelimit() + SignatureProperties.SECRET_KEY));
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
		// 【问暖科技】您的验证码为{1}，请于{2}内正确输入，如非本人操作，请忽略此短信。
		boolean ret = shortMailService.sendSync("243307", phone, new String[]{verifyCode.toString(), String.valueOf(integererval / 60) + "分钟"}, null, null);
		if(!ret) {
			return null;
		}
		return v;
	}

	@Override
	public boolean validate(VerifycodeEntity v) {
		// TODO Auto-generated method stub
		try {
			String datasign = MD5Util.md5Encode(v.getCode() + v.getPhone() + v.getTimelimit() + SignatureProperties.SECRET_KEY);
			if (datasign.equals(v.getDatasign())) {
				return true;
			}
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
		return false;
	}
	
	@Inject private ShortMailService shortMailService;

}
